{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use the retry module or similar alternatives.\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-947765a5574c>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting ./data/t10k-images-idx3-ubyte.gz\n",
      "Extracting ./data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/ai/tool/bin/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = './data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#根据之前sigmoid里的计算结果，将隐层设为1层500个神经元节点,激活函数为tanh\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "#隐层的weight不能init为tf.zeros，否则算出的结果很差\n",
    "w1 = tf.Variable(tf.truncated_normal([784,500],stddev=0.1))\n",
    "b1 = tf.Variable(tf.zeros([500]) + 0.1)\n",
    "layer1 = tf.tanh(tf.matmul(x,w1)+b1)\n",
    "w2 = tf.Variable(tf.truncated_normal([500,300],stddev=0.1))\n",
    "b2 = tf.Variable(tf.zeros([300]) + 0.1)\n",
    "layer2 = tf.tanh(tf.matmul(layer1,w2)+b2)\n",
    "w3 = tf.Variable(tf.truncated_normal([300,10 ],stddev=0.1))\n",
    "b3 = tf.Variable(tf.zeros([10]) + 0.1)\n",
    "y = tf.matmul(layer2, w3) + b3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-5-a1c0d4e99953>:3: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#根据sigmoid里的计算结果，添加l2正则，将正则惩罚因子设为0.0001\n",
    "r = 0.0001\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) + tf.contrib.layers.l2_regularizer(r)(w1) + tf.contrib.layers.l2_regularizer(r)(w2) + tf.contrib.layers.l2_regularizer(r)(w3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train\n",
    "for _ in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.976\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========learning_rate=0.100000========\n",
      "0.2008\n",
      "0.9257\n",
      "0.9428\n",
      "0.9498\n",
      "0.958\n",
      "0.9606\n",
      "0.9648\n",
      "0.9671\n",
      "0.9683\n",
      "0.9685\n",
      "0.9697\n",
      "========learning_rate=0.300000========\n",
      "0.121\n",
      "0.9296\n",
      "0.9575\n",
      "0.962\n",
      "0.9687\n",
      "0.972\n",
      "0.9723\n",
      "0.9738\n",
      "0.9772\n",
      "0.9786\n",
      "0.9797\n",
      "========learning_rate=0.500000========\n",
      "0.1643\n",
      "0.862\n",
      "0.9424\n",
      "0.9513\n",
      "0.9623\n",
      "0.9608\n",
      "0.9593\n",
      "0.968\n",
      "0.9701\n",
      "0.9708\n",
      "0.9716\n",
      "========learning_rate=0.700000========\n",
      "0.2895\n",
      "0.8477\n",
      "0.9114\n",
      "0.9345\n",
      "0.9336\n",
      "0.9318\n",
      "0.9364\n",
      "0.9481\n",
      "0.9589\n",
      "0.9443\n",
      "0.9404\n",
      "========learning_rate=0.900000========\n",
      "0.3204\n",
      "0.3244\n",
      "0.7641\n",
      "0.88\n",
      "0.9182\n",
      "0.9266\n",
      "0.9435\n",
      "0.9507\n",
      "0.9377\n",
      "0.947\n",
      "0.9543\n"
     ]
    }
   ],
   "source": [
    "#学习率调优\n",
    "rate = [0.1,0.3,0.5,0.7,0.9]\n",
    "for i,item in enumerate(rate):\n",
    "    sess = tf.Session()\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    print(\"========learning_rate=%f========\" %(item))\n",
    "    train_step = tf.train.GradientDescentOptimizer(item).minimize(cross_entropy)\n",
    "    for i in range(3000):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        if not i%300:\n",
    "            correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "            print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========learning_rate=0.350000========\n",
      "0.2707\n",
      "0.9439\n",
      "0.957\n",
      "0.9677\n",
      "0.9717\n",
      "0.9705\n",
      "0.9743\n",
      "0.9745\n",
      "0.9777\n",
      "0.9769\n",
      "0.9779\n",
      "========learning_rate=0.400000========\n",
      "0.2736\n",
      "0.9407\n",
      "0.9555\n",
      "0.9672\n",
      "0.9705\n",
      "0.9726\n",
      "0.9742\n",
      "0.9755\n",
      "0.9763\n",
      "0.9789\n",
      "0.9757\n",
      "========learning_rate=0.450000========\n",
      "0.2251\n",
      "0.9443\n",
      "0.9605\n",
      "0.9686\n",
      "0.9705\n",
      "0.9726\n",
      "0.9665\n",
      "0.9759\n",
      "0.9743\n",
      "0.9766\n",
      "0.9783\n",
      "========learning_rate=0.500000========\n",
      "0.3632\n",
      "0.939\n",
      "0.9433\n",
      "0.951\n",
      "0.962\n",
      "0.9685\n",
      "0.9683\n",
      "0.9643\n",
      "0.9704\n",
      "0.9739\n",
      "0.9731\n",
      "========learning_rate=0.550000========\n",
      "0.274\n",
      "0.9184\n",
      "0.9416\n",
      "0.9396\n",
      "0.9477\n",
      "0.957\n",
      "0.9632\n",
      "0.9651\n",
      "0.9667\n",
      "0.9661\n",
      "0.9645\n"
     ]
    }
   ],
   "source": [
    "#学习率调优\n",
    "rate = [0.35,0.4,0.45,0.50,0.55]\n",
    "for i,item in enumerate(rate):\n",
    "    sess = tf.Session()\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    print(\"========learning_rate=%f========\" %(item))\n",
    "    train_step = tf.train.GradientDescentOptimizer(item).minimize(cross_entropy)\n",
    "    for i in range(3000):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        if not i%300:\n",
    "            correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "            print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========learning_rate=0.380000========\n",
      "0.2643\n",
      "0.9325\n",
      "0.9605\n",
      "0.9663\n",
      "0.9703\n",
      "0.9741\n",
      "0.9771\n",
      "0.975\n",
      "0.9786\n",
      "0.9784\n",
      "0.9813\n",
      "========learning_rate=0.390000========\n",
      "0.2478\n",
      "0.9422\n",
      "0.9586\n",
      "0.9657\n",
      "0.9714\n",
      "0.9705\n",
      "0.9737\n",
      "0.9766\n",
      "0.9759\n",
      "0.9776\n",
      "0.979\n",
      "========learning_rate=0.410000========\n",
      "0.3231\n",
      "0.9491\n",
      "0.9587\n",
      "0.9649\n",
      "0.9705\n",
      "0.9703\n",
      "0.9765\n",
      "0.975\n",
      "0.9763\n",
      "0.9762\n",
      "0.9785\n",
      "========learning_rate=0.420000========\n",
      "0.2672\n",
      "0.9488\n",
      "0.9604\n",
      "0.9669\n",
      "0.9705\n",
      "0.974\n",
      "0.9721\n",
      "0.9772\n",
      "0.9779\n",
      "0.9793\n",
      "0.9787\n",
      "========learning_rate=0.430000========\n",
      "0.1778\n",
      "0.9406\n",
      "0.9559\n",
      "0.9674\n",
      "0.9676\n",
      "0.9699\n",
      "0.9767\n",
      "0.9767\n",
      "0.9727\n",
      "0.9782\n",
      "0.98\n",
      "========learning_rate=0.440000========\n",
      "0.3254\n",
      "0.9484\n",
      "0.9584\n",
      "0.967\n",
      "0.9701\n",
      "0.9709\n",
      "0.9728\n",
      "0.9768\n",
      "0.9765\n",
      "0.9774\n",
      "0.9786\n",
      "========learning_rate=0.460000========\n",
      "0.4169\n",
      "0.9469\n",
      "0.9538\n",
      "0.9656\n",
      "0.9581\n",
      "0.9727\n",
      "0.971\n",
      "0.9758\n",
      "0.9781\n",
      "0.9792\n",
      "0.9793\n",
      "========learning_rate=0.470000========\n",
      "0.257\n",
      "0.9015\n",
      "0.9589\n",
      "0.9615\n",
      "0.9616\n",
      "0.9657\n",
      "0.9711\n",
      "0.9697\n",
      "0.9699\n",
      "0.9716\n",
      "0.9729\n",
      "========learning_rate=0.480000========\n",
      "0.3237\n",
      "0.9523\n",
      "0.9553\n",
      "0.9677\n",
      "0.967\n",
      "0.9721\n",
      "0.9716\n",
      "0.9754\n",
      "0.9755\n",
      "0.9769\n",
      "0.9803\n",
      "========learning_rate=0.490000========\n",
      "0.192\n",
      "0.8785\n",
      "0.9298\n",
      "0.9374\n",
      "0.96\n",
      "0.9614\n",
      "0.9688\n",
      "0.9645\n",
      "0.9691\n",
      "0.9724\n",
      "0.9736\n"
     ]
    }
   ],
   "source": [
    "#学习率调优\n",
    "rate = [0.38,0.39,0.41,0.42,0.43,0.44,0.46,0.47,0.48,0.49]\n",
    "for i,item in enumerate(rate):\n",
    "    sess = tf.Session()\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    print(\"========learning_rate=%f========\" %(item))\n",
    "    train_step = tf.train.GradientDescentOptimizer(item).minimize(cross_entropy)\n",
    "    for i in range(3000):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        if not i%300:\n",
    "            correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "            print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从以上计算结果得到，学习率为0.38,0.43或0.48,准确率达到0.98以上"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
